package cloud

import (
	"encoding/json"
	"github.com/goravel/framework/facades"
	"github.com/goravel/framework/support/carbon"
	"github.com/spf13/cast"
	"goravel/app/models"
	"net/http"
)

// 同步云端商品数据
type CloudService struct{}

func NewCloudService() *CloudService {
	return &CloudService{}
}

func (s *CloudService) SyncProduct(code string) (*models.Product, error) {
	url := "http://yun.smda.cc/api/plutest.php?itemcode=" + code
	//定义httpclient客户端发起请求
	client := &http.Client{}
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return nil, err
	}
	body, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	//解析body
	type ProductOrigin struct {
		Code        string `json:"Code"`
		Name        string `json:"Name"`
		Unit        string `json:"Unit"`
		Spec        string `json:"Spec"`
		ProductArea string `json:"product_area"`
		Price       string `json:"price"`
		SalePrice   string `json:"sale_price"`
	}
	bodybuffer := body.Body
	defer bodybuffer.Close()
	var productORG ProductOrigin
	err = json.NewDecoder(bodybuffer).Decode(&productORG)
	if err != nil {
		return nil, err
	}
	product := models.Product{
		Code:           productORG.Code,
		Name:           productORG.Name,
		Unit:           productORG.Unit,
		Spec:           productORG.Spec,
		ShelfLife:      0,
		Store_Condi:    "常温",
		ProductArea:    productORG.ProductArea,
		Price:          cast.ToFloat64(productORG.Price),
		SalePrice:      cast.ToFloat64(productORG.SalePrice),
		Stock:          0,
		SupplierID:     0,
		ProductionDate: carbon.NewDateTime(carbon.Now()),
		ExpireDate:     carbon.NewDateTime(carbon.Now()),
	}
	facades.Orm().Query().Model(&models.Product{}).Create(&product)

	return &product, nil
}
